package com.songlanyun.modules.shop.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.enums.LockPrefixConstant;
import com.songlanyun.common.enums.MemberConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.common.utils.Constant;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.account.service.UserShopRoleService;
import com.songlanyun.modules.exception.MemberException;
import com.songlanyun.modules.exception.ShopException;
import com.songlanyun.modules.shop.dao.ShopApplyDao;
import com.songlanyun.modules.shop.entity.ShopApplyEntity;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.shop.model.dto.ShopApplyDTO;
import com.songlanyun.modules.shop.service.ShopApplyService;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.shop.service.ShopUserRoleConfigService;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service("yxtShopApplyService")
public class ShopApplyServiceImpl extends ServiceImpl<ShopApplyDao, ShopApplyEntity> implements ShopApplyService {

    @Resource
    private AccountService accountService;
    @Resource
    private ShopService shopService;
    @Resource
    private ShopUserRoleConfigService shopUserRoleConfigService;
    @Resource
    private UserShopRoleService userShopRoleService;

    @Value("${shop.mobile}")
    private String lrMobile;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 后台查询所有商家审核列表
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        Integer auditStatus = MapUtil.getInt(params, "audit_status");//审核状态
        String mobile = MapUtil.getStr(params, "mobile");//手机号
        String shopName = MapUtil.getStr(params, "shop_name");//店铺名
        Long userId = MapUtil.getLong(params, "user_id");//店铺名
        String legalRepresentative = MapUtil.getStr(params, "legal_representative");//店铺名
        String lrMobile = MapUtil.getStr(params, "lr_mobile");//法人手机号
        Boolean unionBusiness = MapUtil.getBool(params, "union_business");//是否是联盟商家
        String provinceCode = MapUtil.getStr(params, "province_code");
        String cityCode = MapUtil.getStr(params, "city_code");
        String areaCode = MapUtil.getStr(params, "area_code");

        IPage<ShopApplyEntity> page = this.page(
                new Query<ShopApplyEntity>().getPage(params),
                new LambdaQueryWrapper<ShopApplyEntity>()
                        .eq(auditStatus != null, ShopApplyEntity::getAuditStatus, auditStatus)
                        .eq(userId != null, ShopApplyEntity::getUserId, userId)
                        .like(StringUtils.isNotBlank(mobile), ShopApplyEntity::getMobile, mobile)
                        .like(StringUtils.isNotBlank(shopName), ShopApplyEntity::getShopName, shopName)
                        .like(StringUtils.isNotBlank(legalRepresentative), ShopApplyEntity::getLegalRepresentative, legalRepresentative)//法人名称
                        .like(StringUtils.isNotBlank(lrMobile), ShopApplyEntity::getLrMobile, lrMobile)//法人手机号
                        .ne(ShopApplyEntity::getLrMobile, this.lrMobile)//不用显示平台店铺的申请
                        .eq(ShopApplyEntity::getUnionBusiness, ObjectUtil.isNull(unionBusiness) ? 0 : unionBusiness)//是否是联盟商家

                        .eq(StringUtils.isNotBlank(provinceCode), ShopApplyEntity::getProvinceCode, provinceCode)
                        .eq(StringUtils.isNotBlank(cityCode), ShopApplyEntity::getCityCode, cityCode)
                        .eq(StringUtils.isNotBlank(areaCode), ShopApplyEntity::getAreaCode, areaCode)

                        .orderByDesc(ShopApplyEntity::getUpdateTime)
        );

        return new PageUtils(page);
    }

    /**
     * 平台审核会员申请商家
     *
     * @param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShopApplyEntity audit(ShopApplyDTO dto) {
        RLock lock = redissonClient.getLock(LockPrefixConstant.BECOME_SHOP + dto.getId());
        lock.lock(2, TimeUnit.SECONDS);

        try {
            //该会员如果已经是商家，则不能审核
            ShopApplyEntity shopApplyEntity = this.getById(dto.getId(), true);
            if (shopApplyEntity.getAuditStatus().equals(Constant.PASS)) {//说明该会员已经成为商家，无需审核
                throw new RRException(MemberException.CHECK_IS_PASS);
            }

            //更新审核意见
            ShopApplyEntity apply = this.getById(dto.getId());
            apply.setAudit(dto.getAuditStatus(), dto.getAuditRemark());
            this.updateById(apply);

            //申请通过，则保存商家信息
            if (apply.getAuditStatus().equals(Constant.AUDITPASS)) {

                //会员升级商家后
                //1、保存商家信息
//                ShopEntity shop = setShopByApply(apply);//将审核记录的数据填充到商家中
                ShopEntity shop = apply.loadShop();
                if (ObjectUtil.isNotNull(shop)) {
                    Long shopId = shop.getId();
                    BeanUtil.copyPropertiesIgnoreNull(apply, shop);
                    shop.setId(shopId);
                    shopService.updateById(shop);
                } else {
                    shop = cn.hutool.core.bean.BeanUtil.toBean(apply, ShopEntity.class);
                    shop.setUserId(apply.getUserId());
                    shop.setPlatformShop(false);
                    //联盟商家默认不显示
                    if (shop.getUnionBusiness()) {
                        shop.setIsShow(false);
                    }
                    shopService.save(shop);

                    //2、保存商家的会员等配置
                    shopUserRoleConfigService.saveShopConfig(shop.getId(), true);

                    //查询该店铺会员
                    Long userId = shop.getUserId();//会员id
                    AccountEntity account = accountService.getById(userId);
                    //查询平台店铺id
                    ShopEntity shopEntity = shopService.selectPlatformShop();
                    Long shopId = shopEntity.getId();//平台店铺id

                    //3、会员等级表中的所属店铺改为平台店铺，店铺等级改为市代理
                    //更新当前会员在平台店铺的会员等级记录
                    userShopRoleService.updateLevelByUserAndShop(userId, shopId, MemberConstant.MemberLevel.CITY_AGENT.getCode());

                    //4、将推荐的所有会员都查询出来 （1、parentPath 2、排除店铺 3、排除上级店铺与自己不一致的）
                    String parentPath = account.getParentPath() + account.getId() + ",";
                    Long subjectionShopId = account.getSubjectionShopId();
                    List<Long> accountList = accountService.getSubordinate(parentPath, subjectionShopId);

                    //5、修改这些会员的会员表中的隶属商家
                    accountService.updateByShopId(accountList, shop.getId());

                    //6、克隆会员等级记录（根据推荐的所有会员id和该会员的所属店铺id生成会员等级记录）
                    if (accountList != null && accountList.size() > 0) {
                        userShopRoleService.saveByAccountAndShop(accountList, subjectionShopId, shop.getId());
                    }
                    //7、会员表中的隶属上级商家改为平台商家id
                    account.setSubjectionShopId(shopId);
                    accountService.updateById(account);
                }

            }

            return apply;

        } finally {
            lock.unlock();
        }


    }

    @Override
    public List<ShopApplyEntity> getshopApplyByUserId(Long userId, boolean unionBusiness) {
        List<ShopApplyEntity> list = baseMapper.selectList(
                new LambdaQueryWrapper<ShopApplyEntity>()
                        .eq(ShopApplyEntity::getUserId, userId)
                        .eq(ShopApplyEntity::getUnionBusiness, unionBusiness)
                        .orderByDesc(ShopApplyEntity::getApplyTime)
        );
        return list;
    }

    @Override
    public ShopApplyEntity getOneShopApply(Long userId, boolean unionBusiness) {
        return this.baseMapper.selectOne(
                new LambdaQueryWrapper<ShopApplyEntity>()
                        .eq(ShopApplyEntity::getUserId, userId)
                        .eq(ShopApplyEntity::getUnionBusiness, unionBusiness)
                        .last("limit 1")
        );
    }

    @Override
    public ShopApplyEntity getById(Long id, boolean isThrow) {
        ShopApplyEntity applyEntity = this.baseMapper.selectById(id);
        if (applyEntity == null) {
            if (isThrow) {
                throw new RRException(ShopException.SHOP_APPLY_NOT_EXIST);
            }
        }
        return applyEntity;
    }


    /**
     * 将审核记录的数据填充到商家中,并保存
     */

    @Override
    public ShopEntity saveShopByApply(ShopApplyDTO dto) {
        ShopEntity shop = new ShopEntity();
        shop.setShopName(dto.getShopName());//店铺名称
        shop.setMapPunctuation(dto.getMapPunctuation());//店铺地图标点
        shop.setAddress(dto.getAddress());//地址
        shop.setLogo(dto.getLogo());//店铺logo
        shop.setStoreImages(dto.getStoreImages());//门店图片
        shop.setRemark(dto.getRemark());//店铺简介
        shop.setMobile(dto.getMobile());//手机号
        shop.setProvinceCode(dto.getProvinceCode());//省编号
        shop.setProvinceName(dto.getProvinceName());//省名称
        shop.setCityCode(dto.getCityCode());//市编号
        shop.setCityName(dto.getCityName());//市名称
        shop.setAreaCode(dto.getAreaCode());//区编号
        shop.setAreaName(dto.getAreaName());//区名称
        shop.setMainName(dto.getMainName());
        shop.setCustomerServicePhone(dto.getCustomerServicePhone());
        shop.setPlaceRemark(dto.getPlaceRemark());
        shop.setLoser(dto.getLoser());
        shop.setAddress(dto.getAddress());

        shop.setBusinessHours(dto.getBusinessHours());//营业时间
        shop.setTimeQuantum(dto.getTimeQuantum());//时间段
        shop.setTxLongitude(dto.getTxLongitude());//微信经度
        shop.setTxLatitude(dto.getTxLatitude());//微信维度

        return shop;
    }

    @Override
    public ShopEntity setShopByApply(ShopApplyEntity apply) {
        ShopEntity shop = new ShopEntity();
        shop.setUserId(apply.getUserId());//会员id
        shop.setShopName(apply.getShopName());//店铺名称
        shop.setMapPunctuation(apply.getMapPunctuation());//店铺地图标点
        shop.setAddress(apply.getAddress());//地址
        shop.setLogo(apply.getLogo());//店铺logo
        shop.setStoreImages(apply.getStoreImages());//门店图片
        shop.setRemark(apply.getRemark());//店铺简介
        shop.setMobile(apply.getMobile());//手机号
        shop.setProvinceCode(apply.getProvinceCode());//省编号
        shop.setProvinceName(apply.getProvinceName());//省名称
        shop.setCityCode(apply.getCityCode());//市编号
        shop.setCityName(apply.getCityName());//市名称
        shop.setAreaCode(apply.getAreaCode());//区编号
        shop.setAreaName(apply.getAreaName());//区名称

        shop.setLoser(apply.getLoser());
        shop.setCustomerServicePhone(apply.getCustomerServicePhone());
        shop.setMainName(apply.getMainName());
        shop.setPlaceRemark(apply.getPlaceRemark());

        shop.setBusinessHours(apply.getBusinessHours());//营业时间
        shop.setTimeQuantum(apply.getTimeQuantum());//时间段
        shop.setTxLongitude(apply.getTxLongitude());//微信经度
        shop.setTxLatitude(apply.getTxLatitude());//微信维度
        shop.setPlatformShop(false);//是否是平台商家 0：不是 1：是
        shop.setUnionBusiness(apply.getUnionBusiness());//是否是联盟商家

        return shop;
    }

    /**
     * 根据会员id查询商家申请记录  -- 企业信息
     *
     * @param userId
     * @return
     */
    @Override
    public ShopApplyEntity getApplyByUserId(Long userId, boolean unionBusiness) {
        return this.baseMapper.selectOne(
                new LambdaQueryWrapper<ShopApplyEntity>()
                        .eq(ShopApplyEntity::getUserId, userId)
                        .eq(ShopApplyEntity::getUnionBusiness, unionBusiness)
                        .eq(ShopApplyEntity::getAuditStatus, Constant.AUDITPASS)
                        .last("limit 1")
        );

    }

    @Override
    public ShopApplyEntity initApply(ShopApplyDTO dto, Long userId) {
        ShopApplyEntity shopApplyEntity = new ShopApplyEntity();
        BeanUtil.copyPropertiesIgnoreNull(dto, shopApplyEntity);
        shopApplyEntity.setAudit(Constant.AUDITPASS, "平台商家自动审核");
        shopApplyEntity.setUserId(userId);
        this.baseMapper.insert(shopApplyEntity);
        return shopApplyEntity;
    }

    @Override
    public ShopApplyEntity copyAndSave(ShopApplyDTO dto) {
        ShopApplyEntity shopApplyEntity = new ShopApplyEntity();
        BeanUtil.copyPropertiesIgnoreNull(dto, shopApplyEntity);
        this.baseMapper.insert(shopApplyEntity);
        return shopApplyEntity;
    }

}
